package com.clouduserservice8001.controller;

import com.clouduserservice8001.common.Result;
import com.clouduserservice8001.entity.Employee;
import com.clouduserservice8001.dto.EmployeeVO;
import com.clouduserservice8001.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 员工管理控制器
 */
@RestController
@RequestMapping("/api/employees")
public class EmployeeController {
    
    @Autowired
    private EmployeeService employeeService;
    
    /**
     * 创建员工
     */
    @PostMapping
    public Result<Void> createEmployee(@RequestBody Employee employee, @RequestParam("createBy") String createBy) {
        if (employee.getUserId() == null || employee.getUserId().trim().isEmpty()) {
            return Result.error("关联用户ID不能为空");
        }
        
        // 检查员工工号是否已存在（如果提供了工号）
        if (employee.getEmployeeNo() != null && !employee.getEmployeeNo().trim().isEmpty()) {
            if (employeeService.isEmployeeNoExists(employee.getEmployeeNo())) {
                return Result.error("员工工号已存在");
            }
        }
        
        boolean success = employeeService.createEmployee(employee, createBy);
        if (success) {
            return Result.<Void>success("员工创建成功", null);
        } else {
            return Result.error("员工创建失败");
        }
    }
    
    /**
     * 更新员工信息
     */
    @PutMapping("/{userId}")
    public Result<Void> updateEmployee(@PathVariable("userId") String userId, @RequestBody Employee employee, @RequestParam("updateBy") String updateBy) {
        employee.setUserId(userId);
        boolean success = employeeService.updateEmployee(employee, updateBy);
        if (success) {
            return Result.<Void>success("员工信息更新成功", null);
        } else {
            return Result.error("员工信息更新失败");
        }
    }
    
    /**
     * 删除员工（逻辑删除）
     */
    @DeleteMapping("/{userId}")
    public Result<Void> deleteEmployee(@PathVariable("userId") String userId, @RequestParam("updateBy") String updateBy) {
        boolean success = employeeService.deleteEmployee(userId, updateBy);
        if (success) {
            return Result.<Void>success("员工删除成功", null);
        } else {
            return Result.error("员工删除失败");
        }
    }
    
    /**
     * 更新员工状态
     */
    @PutMapping("/{userId}/status")
    public Result<Void> updateEmployeeStatus(@PathVariable("userId") String userId, @RequestParam("status") String status, @RequestParam("updateBy") String updateBy) {
        if (!"0".equals(status) && !"1".equals(status)) {
            return Result.error("状态值无效");
        }
        
        boolean success = employeeService.updateEmployeeStatus(userId, status, updateBy);
        if (success) {
            String message = "1".equals(status) ? "员工状态设为在职" : "员工状态设为离职";
            return Result.<Void>success(message, null);
        } else {
            return Result.error("员工状态更新失败");
        }
    }
    
    /**
     * 根据用户ID查询员工详细信息（包含用户基本信息）
     */
    @GetMapping("/user/{userId}")
    public Result<EmployeeVO> getEmployeeByUserId(@PathVariable("userId") String userId) {
        EmployeeVO employee = employeeService.getEmployeeVOByUserId(userId);
        if (employee != null) {
            return Result.success(employee);
        } else {
            return Result.error("员工不存在");
        }
    }

    /**
     * 根据员工工号查询员工详细信息（包含用户基本信息）
     */
    @GetMapping("/no/{employeeNo}")
    public Result<EmployeeVO> getEmployeeByEmployeeNo(@PathVariable("employeeNo") String employeeNo) {
        EmployeeVO employee = employeeService.getEmployeeVOByEmployeeNo(employeeNo);
        if (employee != null) {
            return Result.success(employee);
        } else {
            return Result.error("员工不存在");
        }
    }

    /**
     * 查询员工详细信息列表（包含用户基本信息）
     */
    @GetMapping
    public Result<List<EmployeeVO>> getEmployeeList(@RequestParam(value = "deptName", required = false) String deptName,
                                                   @RequestParam(value = "status", required = false) String status,
                                                   @RequestParam(value = "keyword", required = false) String keyword) {
        List<EmployeeVO> employees = employeeService.getEmployeeVOList(deptName, status, keyword);
        return Result.success(employees);
    }

    /**
     * 根据部门查询员工详细信息列表（包含用户基本信息）
     */
    @GetMapping("/dept/{deptName}")
    public Result<List<EmployeeVO>> getEmployeesByDept(@PathVariable("deptName") String deptName) {
        List<EmployeeVO> employees = employeeService.getEmployeeVOsByDept(deptName);
        return Result.success(employees);
    }

    /**
     * 根据上级ID查询下属员工详细信息列表（包含用户基本信息）
     */
    @GetMapping("/manager/{managerId}")
    public Result<List<EmployeeVO>> getEmployeesByManager(@PathVariable("managerId") String managerId) {
        List<EmployeeVO> employees = employeeService.getEmployeeVOsByManager(managerId);
        return Result.success(employees);
    }
    
    /**
     * 生成员工工号
     */
    @GetMapping("/generate-no")
    public Result<String> generateEmployeeNo() {
        String employeeNo = employeeService.generateEmployeeNo();
        return Result.success("员工工号生成成功", employeeNo);
    }
    
    /**
     * 检查员工工号是否存在
     */
    @GetMapping("/check-no/{employeeNo}")
    public Result<Boolean> checkEmployeeNoExists(@PathVariable("employeeNo") String employeeNo) {
        boolean exists = employeeService.isEmployeeNoExists(employeeNo);
        return Result.success(exists);
    }
}
